package com.blog.controller;


import com.blog.check.result.Result;
import com.blog.form.LoginForm;
import com.blog.service.service.LoginService;
import org.apache.http.HttpStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 泡面ing
 * @date 2021/11/17
 */
@Controller
@RequestMapping("/login")
public class LoginController {

    @Resource
    private LoginService loginService;

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @RequestMapping(method = RequestMethod.POST)
    @ResponseBody
    public Result login(@RequestBody LoginForm loginForm, HttpServletRequest request, HttpServletResponse response){
        Result result;
        try{
            result = loginService.login(loginForm,request);
            if (result.getCode() != Result.SUCCESS) {
                response.sendError(HttpStatus.SC_UNAUTHORIZED,"账号或密码错误");
                return result;
            }
            response.setStatus(HttpStatus.SC_CREATED);
        }catch (Exception e){
            response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            result = Result.failure(HttpStatus.SC_INTERNAL_SERVER_ERROR, "系统异常：" + e.getMessage());
            logger.error("登录异常:", e);
        }
        return result;
    }

    @RequestMapping(value = "/logout",method = RequestMethod.POST)
    @ResponseBody
    public Result logout(HttpServletResponse response){
        Result result;
        try{
            result = loginService.logout();
            if (result.getCode() != Result.SUCCESS) {
                response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
                return result;
            }
            response.setStatus(HttpStatus.SC_CREATED);
        }catch (Exception e){
            response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            result = Result.failure(HttpStatus.SC_INTERNAL_SERVER_ERROR, "系统异常：" + e.getMessage());
            logger.error("登录异常:", e);
        }
        return result;
    }
}
